<template>
  <div>
    <div>
      <FormEdit :data-form="formData0" />
    </div>
    <div class="checked-device">
      <div class="checked-device-title"><span>保养设备</span></div>
      <h-table-list
        border
        type="local"
        :data="tableData"
        :show-pagination="false"
        :columns="columns"
      >
        <!-- <ListOpearteButton /> -->
        <el-button @click="addCheckedDevice">添加保养设备</el-button>
        <span>只可选择台账状态【启用】的设备，提交审批后不可更改</span>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <!-- <el-button>上传保养部位简图</el-button> -->
          <el-button
            size="mini"
            @click="deleteDeviceData(scope.$index)"
          >删除</el-button>

        </template>
      </h-table-list>
    </div>
    <div class="checked-device">
      <div class="checked-device-title"><span>保养项</span></div>
      <el-button @click="addCheckedItems">添加保养项</el-button>
      <el-button @click="addCheckedNocontentItem">添加空白保养项</el-button>
      <el-form
        ref="productRuleForm"
        :model="productRuleForm"
        :rules="productRuleForm.rules"
        :show-message="false"
      >
        <h-table-list
          border
          type="local"
          :data="productRuleForm.tableData"
          :show-pagination="false"
          :columns="column2s"
        >
          <!--用插槽templete占位替换自定义部分 -->
          <template
            slot="operate-part"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.part'"
              :rules="productRuleForm.rules.part"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].part" />
            </el-form-item>
          </template>
          <template
            slot="operate-content"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.content'"
              :rules="productRuleForm.rules.content"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].content" />
            </el-form-item>
          </template>
          <template
            slot="operate-standard"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.standard'"
              :rules="productRuleForm.rules.standard"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].standard" />
            </el-form-item>
          </template>
          <template
            slot="operate-method"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.method'"
              :rules="productRuleForm.rules.method"
            >
              <el-input v-model="productRuleForm['tableData'][scope.$index].method" />
            </el-form-item>
          </template>
          <template
            slot="operate-upPicFlag"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.upPicFlag'"
              :rules="productRuleForm.rules.upPicFlag"
            >
              <el-select v-model="productRuleForm['tableData'][scope.$index].upPicFlag">
                <el-option
                  :value="0"
                  :label="'不上传'"
                />
                <el-option
                  :value="1"
                  :label="'选填'"
                />
                <el-option
                  :value="2"
                  :label="'必填'"
                />
              </el-select>
            </el-form-item>
          </template>
          <template
            slot="operate-upVideoFlag"
            slot-scope="scope"
          >
            <el-form-item
              :prop="'tableData.' + scope.$index + '.upVideoFlag'"
              :rules="productRuleForm.rules.upVideoFlag"
            >
              <el-select v-model="productRuleForm['tableData'][scope.$index].upVideoFlag">
                <el-option
                  :value="0"
                  :label="'不上传'"
                />
                <el-option
                  :value="1"
                  :label="'选填'"
                />
                <el-option
                  :value="2"
                  :label="'必填'"
                />
              </el-select>
            </el-form-item>
          </template>
          <template
            slot="operate-button"
            slot-scope="scope"
          >

            <el-button
              size="mini"
              @click="moveProTableData(scope.$index, scope.$index - 1)"
            >上移</el-button>
            <el-button
              size="mini"
              @click="moveProTableData(scope.$index, scope.$index + 1)"
            >下移</el-button>
            <el-button
              size="mini"
              @click="deleteProTableData(scope.$index)"
            >删除</el-button>
          </template>
        </h-table-list>
      </el-form>
    </div>

    <div>
      <FormEdit :data-form="operateForm0" />
    </div>
    <div class="check-device-buttons">
      <el-button
        type="primary"
        class="submit_btn"
        @click="() => submit(0)"
      >存草稿</el-button>
      <el-button
        type="primary"
        class="submit_btn"
        @click="() => submit(1)"
      >提交</el-button>
      <CacelButton />
    </div>
    <DownloadIdentify
      :visible.sync="dialogDeviceVisible"
      title="添加保养设备"
      @cancel="cancel"
      @update="addChooseDevices"
    >
      <h-table-list
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="deviceBasic.records"
        :columns="columns1s"
        :pagination-info="paginationInfo"
        :form-options="formOptions2s"
        @selection-change="handleSelectionChange"
      >
        <template
          slot="preview-column"
          slot-scope="scope"
        >
          <p>{{ scope.row.status }}</p>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </DownloadIdentify>
    <DownloadIdentify
      :visible.sync="dialogPartVisible"
      title="添加保养项目"
      @cancel="cancel"
      @update="addChooseItems"
    >
      <h-table-list
        ref="addCheckDeviceTable"
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="device_preserve_items.records"
        :columns="column3s"
        :form-options="formOptions2s"
        :pagination-info="paginationInfo2"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionItemsChange"
      >
        <template
          slot="preview-column"
          slot-scope="scope"
        >
          <p>{{ scope.row.status }}</p>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import FormEdit from "@/components/formEdit/index";
import ListOpearteButton from "@/components/AllButton/button2";
import CacelButton from "@/components/AllButton/cancel";
import DownloadIdentify from "@/components/FormDialog";
import data from "./const";
import { uniComplexArr } from "@/utils";
export default {
  components: { FormEdit, ListOpearteButton, DownloadIdentify, CacelButton },

  data() {
    return {
      // 保养项数据
      productRuleForm: {
        tableData: [
          // {
          //   part: "", //保养部位
          //   content: "", //保养内容
          //   standard: "", //保养基准 非必须
          //   method: "", //保养方法 非必须
          //   upPicFlag: 0, //上传图片 0不上传 1选填 2必填
          //   upVideoFlag: 0, //上传图片 0不上传 1选填 2必填
          // },
        ],
        rules: {
          part: [{ required: true, message: "请选择日期", trigger: "blur" }],
          content: [{ required: true, message: "请输入姓名", trigger: "blur" }],
          standard: [
            { required: true, message: "请输入电话号码", trigger: "blur" }
          ],
          method: [{ required: true, message: "请输入地址", trigger: "blur" }],
          upPicFlag: [
            { required: true, message: "请输入地址", trigger: "blur" }
          ],
          upVideoFlag: [
            { required: true, message: "请输入地址", trigger: "blur" }
          ]
        }
      },
      chooseDevices: [],
      chooseItems: [],
      formOptions2s: {
        inline: true,
        submitBtnText: "搜索",
        showResetBtn: true,
        searchParamsHandler: () => {
          console.log("搜索");
          this.getItemsList(
            this.$store.state.device_preserve_items.listSearchParams
          );
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params);
          this.$store.dispatch(
            "device_preserve_items/setListSearchParams",
            params
          );
        },
        resetBtnCallback: () => {
          this.$store.dispatch("device_preserve_items/setListSearchParams", {});
          this.getList(
            this.$store.state.device_preserve_items.listSearchParams
          );
        },
        forms: [
          { prop: "groupName", label: "分组" },

          { prop: "part", label: "保养部位" },
          { prop: "content", label: "保养内容" }
          // {
          //   prop: "useDepartmentId",
          //   label: "归属部门",
          //   itemType: "select",
          //   options: [
          //     { value: "", label: "部门1" },
          //     { value: 0, label: "部门2" },
          //     { value: 1, label: "部门3" },
          //   ],
          // },

          // {
          //   prop: "positionsId",
          //   label: "职位",
          //   itemType: "select",
          //   options: [
          //     { value: 0, label: "通用" },
          //     { value: 1, label: "专用" },
          //   ],
          // },
          //  {
          //   prop: "userType",
          //   label: "账号类别",
          //   itemType: "select",
          //   options: [
          //     { value: "0", label: "手机" },
          //     { value: "1", label: "PC" },
          //   ],
          // },
        ]
      },
      dialogDeviceVisible: false,
      dialogPartVisible: false,
      paginationInfo: {
        sizeChange: e => {
          console.log(e);
        },
        currentChange: e => {
          this.$store.dispatch("deviceBasic/setListSearchParams", {
            current: e
          });
          this.getList(
            Object.assign({}, this.$store.state.deviceBasic.listSearchParams)
          );
        },
        current: 1,
        total: 10
      },
      paginationInfo2: {
        sizeChange: e => {
          console.log(e);
        },
        currentChange: e => {
          this.$store.dispatch("device_preserve_items/setListSearchParams", {
            current: e
          });
          this.getList(
            Object.assign(
              {},
              this.$store.state.device_preserve_items.listSearchParams
            )
          );
        },
        current: 1,
        total: 10
      },
      tableData: [],
      tableData2s: [
        { id: 0, checkContent: "22" },
        { id: 1, checkContent: "22" },
        { id: 2, checkContent: "22" }
      ],
      tableData3s: [],
      data,
      formData0: data.basicForm0,
      operateForm0: data.operateForm0,
      columns: [
        { type: "index", label: "序号", width: 140 },

        {
          prop: "deviceName",
          label: "设备名称",
          minWidth: 180
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: "assetNumber",
          label: "设备编号",
          minWidth: 180
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.deviceNumber ? deviceInfo.deviceNumber :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: "organName", label: "使用部门", minWidth: 180 },
        { prop: "departmentName", label: "保养部位简图", minWidth: 180 },
        {
          prop: "operate",
          label: "操作",
          minWidth: 200,
          // minWidth: 180,
          slotName: "operate-column"
          // fixed: "right",
        }
      ],
      columns1s: [
        { type: "selection", label: "序号" },
        { prop: "deviceName", label: "设备名称" },
        { prop: "assetCode", label: "固定资产编码" },

        { prop: "assetNumber", label: "设备编号" },
        { prop: "deviceClass", label: "设备类别" },
        { prop: "typeId", label: "设备分类" },
        {
          prop: "organName",
          label: "使用部门"
        },

        { prop: "responsible", label: "责任人" },
        { prop: "deviceModel", label: "型号" }
      ],
      column2s: [
        { type: "index", label: "序号" },
        {
          prop: "part",
          label: "保养部位",
          slotName: "operate-part",
          minWidth: 200
        },
        {
          prop: "content",
          label: "保养内容",
          slotName: "operate-content",
          minWidth: 200
        },

        {
          prop: "standard",
          label: "保养基准",
          slotName: "operate-standard",
          minWidth: 200
        },
        {
          prop: "method",
          label: "保养方法",
          slotName: "operate-method",
          minWidth: 200
        },
        // { prop: "upPicFlag", label: "上传图片",slotName:"operate-upPicFlag"},
        // {
        //   prop: "upVideoFlag",
        //   label: "上传视频",slotName:"operate-upVideoFlag"
        // },

        {
          prop: "responsible",
          label: "操作",
          slotName: "operate-button",
          minWidth: 200
        }
      ],
      column3s: [
        { type: "selection", label: "序号" },

        { prop: "groupName", label: "分组", minWidth: 200 },

        {
          prop: "part",
          label: "保养部位",
          minWidth: 200

          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: "content",
          label: "保养内容",
          minWidth: 200
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.content ? deviceInfo.content :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: "standard", label: "保养基准", minWidth: 200 },
        { prop: "method", label: "保养方法", minWidth: 200 },
        // {
        //   prop: "itemsSum",
        //   label: "保养项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        {
          prop: "upPicFlag",
          label: "上传图片",
          minWidth: 180,
          filter: "formatIsNecessary"
        },
        {
          prop: "upVideoFlag",
          label: "上传视频",
          minWidth: 180,
          filter: "formatIsNecessary"
        }
        // {
        //   prop: "createdTime",
        //   label: "创建时间",
        //   minWidth: 180,
        // //  slotName: "createdTime",
        // },
      ]
    };
  },
  watch: {
    // 这里处理为数据监听改变form的配置来实现业务上的模板更换,后续考虑优化
    "data.basicForm0.0.formModel.planPeriodType": {
      handler: function(val) {
        console.log("深度监听", val);
        if (val == 0) {
          // 定期
          this.formData0 = this.data.basicForm0;
          console.log(this.formData0);
        } else if (val == 1) {
          // 日常
          this.formData0 = this.data.basicForm1;
          console.log(this.formData0);
        }
      },
      deep: true,
      immediate: true
    },
    "data.operateForm0.0.formModel.membType": {
      handler: function(val) {
        console.log("深度监听", val);
        if (val == "0") {
          // 指定人员
          this.operateForm0 = this.data.operateForm0;
        } else if (val == "1") {
          // 指定部门
          this.operateForm0 = this.data.operateForm1;
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    ...mapState(["deviceBasic", "app", "device_preserve_items"])
  },
  mounted() {
    // 先判断有无数据，是新增还是编辑
    const { fullPath } = this.$route;
    const id = localStorage.getItem(fullPath);
    if (id) {
      // 存在id时则请求拉取详情
      this.$store
        .dispatch("device_preserve_plan/requestDeviceDetailInfo", id)
        .then(res => {
          console.log(res, "++++++requestDeviceDetailInfo++++++");

          let resInfo = JSON.parse(JSON.stringify(res.data));
          resInfo.preserveType = res.data.preserveType.toString();
          resInfo.planPeriodType = res.data.planPeriodType.toString();
          resInfo.membType = res.data.membType.toString();
          resInfo.dailyPeriodType = res.data.dailyPeriodType.toString();
          //  resInfo.userId = res.data.userId + "," + res.data.userName;

          // 四部分数值回填
          this.$set(this.formData0[0], "formModel", resInfo);
          this.$set(this.productRuleForm, "tableData", res.data.planItems);
          this.$set(this, "tableData", [res.data]);
          this.$set(this.operateForm0[0], "formModel", resInfo);
          console.log(this, "+++this+++");
        })
        .catch(err => {});
    } else {
      console.log("新增保养计划");
    }

    // 加载保养设备和保养项
    this.getDeviceList({ state: 13 });
    this.getItemsList();
  },
  // destroyed() {
  //   this.formData0[0].formModel = data.basicForm0[0].formModel;
  //   this.$store.dispatch("device_preserve_items/clearAll");
  // },
  methods: {
    //上移、下移
    moveProTableData(from, to) {
      if (!this.productRuleForm || !this.productRuleForm.tableData) {
        return;
      }

      const arr = this.productRuleForm.tableData;
      console.log(arr, "++++arr+++=");

      // 检测移动边界
      if (to < 0 || to > arr.length - 1) {
        return;
      }
      // 移动元素
      const moveTarget = arr.splice(from, 1)[0];
      arr.splice(to, 0, moveTarget);
      this.productRuleForm.tableData = arr;
    },
    //删除
    deleteProTableData(index) {
      if (!this.productRuleForm || !this.productRuleForm.tableData) {
        return;
      }

      const arr = this.productRuleForm.tableData;
      // 检测边界
      if (index < 0 || index > arr.length - 1) {
        return;
      }
      arr.splice(index, 1);
      this.productRuleForm.tableData = arr;
    },

    //删除保养设备
    deleteDeviceData(index) {
      if (!this.tableData || this.tableData.length <= 0) {
        return;
      }

      const arr = this.tableData;
      // 检测边界
      if (index < 0 || index > arr.length - 1) {
        return;
      }
      arr.splice(index, 1);
      this.tableData = arr;
    },
    async getItemsList(args) {
      // this.listLoading = true
      console.log(args);
      await this.$store.dispatch(
        "device_preserve_items/requestDeviceList",
        args
      );
      this.paginationInfo2.total = this.$store.state.device_preserve_items.total;
    },
    handleFilter2(args) {
      this.listQuery.page = 1;
      this.getList(args);
    },
    async getDeviceList(args) {
      // this.listLoading = true
      console.log(args);
      await this.$store.dispatch("deviceBasic/requestDeviceList", args);
      this.paginationInfo.total = this.$store.state.deviceBasic.total;
    },
    handleFilter(args) {
      this.listQuery.page = 1;
      this.getDeviceList(args);
    },
    addCheckedDevice() {
      console.log("添加点位设备");
      this.dialogDeviceVisible = true;
    },
    addCheckedItems() {
      console.log("添加点位项目");
      this.dialogPartVisible = true;
    },
    addCheckedNocontentItem() {
      // 添加空白保养项
      // this.tableData2s.push({id:this.tableData2s.length})
      this.productRuleForm.tableData.push({
        date: "",
        name: "",
        phone: "",
        address: ""
      });
    },
    handleSelectionChange(row) {
      console.log("选择保养设备", row);
      this.chooseDevices = row;
    },
    handleSelectionItemsChange(row) {
      console.log("选择保养项目", row);
      this.chooseItems = row;
    },
    addChooseDevices(row) {
      console.log(this.chooseDevices);
      this.tableData = this.chooseDevices;
      // this.tableData=uniComplexArr(this.tableData)
      this.dialogDeviceVisible = false;
    },
    addChooseItems(row) {
      console.log(this.chooseItems);
      this.productRuleForm.tableData = this.chooseItems;
      this.$set(this.productRuleForm, "tableData", this.chooseItems);
      console.log(this.tableData2s);
      // this.tableData=uniComplexArr(this.tableData)
      this.dialogPartVisible = false;
    },

    // 提交数据
    submit(status) {
      this.$refs["productRuleForm"].validate(valid => {
        const items = {
          assets: this.chooseDevices.map(e => {
            e.useOrganId = e.organId;
            e.useOrganName = e.organName;
            return e;
          }),
          items: this.productRuleForm.tableData,
          subCode: status // 0存草稿 1提交审批
        };
        let membData = this.operateForm0[0].formModel.membId;
        console.log(membData, "++++membData+++++");

        //(this.operateForm0)[0].formModel.membName=membData.split(",")[1]
        //(this.operateForm0)[0].formModel.membId=membData.split(",")[0]
        let membDataObj = {};
        if (typeof membData != "number" && membData.indexOf(",") != -1) {
          membDataObj = {
            membName: membData.split(",")[1],
            membId: membData.split(",")[0]
          };
        } else {
          membDataObj = { membId: membData };
        }
        const data = Object.assign(
          {},
          items,
          this.formData0[0].formModel,
          this.operateForm0[0].formModel,
          membDataObj
        );
        if (data.regularTime && data.regularTime.length > 0) {
          data.regularStartTime =
            data.regularTime[0].slice(0, 10) + " 00:00:00";
          data.regularEndTime = data.regularTime[1].slice(0, 10) + " 23:59:59";
        }

        console.log(data, "++++submit data++++");
        this.$store
          .dispatch("device_preserve_plan/saveDeviceInfo", data)
          .then(response => {
            this.$store.dispatch("tagsView/delVisitedView", {
              path: this.$route.fullPath
            });
            this.$router.push("/device-preserve/plan");
          });
      });
    }
  }
};
</script>

<style lang="scss">
.checked-device {
  background: white;
  margin: 10px 0;
  padding: 20px;
  .checked-device-title {
    margin: 10px 0;
    font-size: 16px;
  }
}
.check-device-buttons {
  margin: 20px 0;
  text-align: center;
}
</style>
